<template>
    <panel-head :route="route" />
    <div class="btn">
        <el-button :icon="Plus" type="primary" @click="open" size="small">新增</el-button>
    </div>
    <el-table :data="tableData.list" style="width: 100%">
        <el-table-column prop="id" label="id" />
        <el-table-column prop="name" label="昵称" />
        <el-table-column prop="permissionName" label="菜单权限" width="500px" />
        <el-table-column label="操作">
            <template #default="scope">
                <div>
                    <el-button type="primary" @click="open(scope.row)">编辑</el-button>
                </div>
            </template>
        </el-table-column>
    </el-table>
    <div class="pagination-info">
        <el-pagination
            v-model:current-page="pagination.pageNum"
            :page-size="pagination.pageSize"
            :background="false"
            size="small"
            layout="total, prev, pager, next"
            :total="tableData.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <el-dialog
        v-model="dialogFormVisible"
        :before-close="beforeClose"
        title="添加权限"
        width="500px"
    >
        <el-form 
            ref="formRef"
            :rules="rules"
            :model="formData"
            label-width="100px"
            label-position="left"
        >
            <el-form-item label="名称" prop="name">
                <el-input v-model="formData.name" />
            </el-form-item>
            <el-form-item label="权限" prop="permissions">
                <el-tree
                    ref="treeRef"
                    style="max-width: 600px"
                    :data="treeData"
                    show-checkbox
                    node-key="id"
                    :default-checked-keys="[2, 4, 5]"
                    :default-expanded-keys="[2, 4, 5]"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <div>
                <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { getMenuData, setMenuData, getMenuPermissionsList } from '@/api'
import { Plus } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'

const route = useRoute()
// 拿到表单实例
const formRef = ref(null)
// 拿到树形组件实例
const treeRef = ref(null)

// 是否显示对话框
const dialogFormVisible = ref(false)
// 表单数据
const formData = reactive({
    id: '',
    name: '',
    permissions: ''
})
const pagination = reactive({
    pageNum: 1,
    pageSize: 10
})
const tableData = reactive({
    list: [],
    total: 0,
})

// 获取菜单权限列表
const getMenuList = () => {
    getMenuPermissionsList(pagination).then(({ data }) => {
        tableData.list = data.data.list
        tableData.total = data.data.total
    })
}
// 菜单权限数据
const treeData = ref([])
onMounted(() => {
    getMenuData().then(({ data }) => {
        console.log(data)
        treeData.value = data.data
    })
    getMenuList()
})

// 打开表单
const open = (rowData = {}) => {
    dialogFormVisible.value = true
    nextTick(() => {
        // 判断是否是编辑操作
        if (rowData) {
            // id = rowData.id
            // formData.name = rowData.name
            // formData.permissions = rowData.permission
            // 此种写法会丢失响应式
            Object.assign(formData, { id: rowData.id, name: rowData.name })
            // 选中的权限
            treeRef.value.setCheckedKeys(rowData.permission)
        }
    })
}

// 弹框关闭前的回调
const beforeClose = () => {
    dialogFormVisible.value = false
    // 清空表单数据
    formRef.value.resetFields()
    // 手动设置权限
    treeRef.value.setCheckedKeys([2, 4, 5])
}
// 表单校验
const rules = reactive({
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' }
    ]
})

// 提交表单
const submitForm = async (formEl) => {
    // 如果没有获取到表单实例对象，直接返回
    if (!formEl) return
    // 如果获取到表单实例对象，调用表单校验方法手动校验需要校验的表单项
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 获取选中的权限
            const permissions = JSON.stringify(treeRef.value.getCheckedKeys())
            // 点击提交表单，创建新的权限
            setMenuData({ name: formData.name, permissions, id: formData.id}).then(() => {
                beforeClose()
                getMenuList()
            })
            dialogFormVisible.value = false
        } else {
            console.log('错误提交')
        }
    })
}

// 分页相关
const handleSizeChange = (val) => {
    pagination.pageSize = val
    getMenuList()
}
const handleCurrentChange = (val) => {
    pagination.pageNum = val
    getMenuList()
}
</script>

<style lang="less" scoped>
.btn {
    padding: 10px 0 10px 10px;
    background-color: #fff;
}
</style>